<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Title</title>
  <script src="js/paho-mqtt.js"></script>
</head>

<body>
<div>
  <h3>配置</h3>
  <label for="ipText">IP：</label>
  <input id="ipText" type="text" value="127.0.0.1">
  <br>
  <label for="portNumber">端口：</label>
  <input id="portNumber" type="number" value="15675">
  <br>
  <label for="usernameText">用户名：</label>
  <input id="usernameText" type="text">
  <br>
  <label for="passwordText">密码：</label>
  <input id="passwordText" type="text">
  <br>
  <label for="connectionTimeoutNumber">连接超时时间(秒)：</label>
  <input id="connectionTimeoutNumber" type="number" value="30">
  <br>
  <label for="keepAliveIntervalNumber">保活时间(秒)：</label>
  <input id="keepAliveIntervalNumber" type="number" value="60">
  <br>
  <label for="cleanSessionCheckbox">清除会话：</label>
  <input id="cleanSessionCheckbox" type="checkbox" checked>
  <br>
  <label for="automaticReconnectCheckbox">自动重连：</label>
  <input id="automaticReconnectCheckbox" type="checkbox" checked>
  <br>
  <label for="topicText">订阅主题：</label>
  <input id="topicText" type="text" value="#">
  <br>
  <button id="connectBtn">连接</button>
  <h4>连接错误信息：</h4>
  <textarea id="errorMsg" readonly cols="30" rows="3"></textarea>
</div>
<div>
  <h3>发送</h3>
  <label for="sendTopicText">主题：</label><input id="sendTopicText" type="text">
  <br>
  <label for="sendMsgText">消息：</label><input id="sendMsgText" type="text">
  <br>
  <label for="sendQosNumber">QoS：</label>
  <input id="sendQosNumber" type="number" value="0">
  <br>
  <label for="sendRetainCheckbox">保留：</label>
  <input id="sendRetainCheckbox" type="checkbox">
  <br>
  <button id="sendBtn" disabled>发送</button>
</div>
<div>
  <h3>消息</h3>
  <textarea id="receiveMsgText" readonly cols="30" rows="6"></textarea>
</div>
<script>
</script>
</body>
<script>
  const ipText = document.getElementById('ipText')
  const portNumber = document.getElementById('portNumber')
  const usernameText = document.getElementById('usernameText')
  const passwordText = document.getElementById('passwordText')
  const connectionTimeoutNumber = document.getElementById('connectionTimeoutNumber')
  const keepAliveIntervalNumber = document.getElementById('keepAliveIntervalNumber')
  const cleanSessionCheckbox = document.getElementById('cleanSessionCheckbox')
  const automaticReconnectCheckbox = document.getElementById('automaticReconnectCheckbox')
  const topicText = document.getElementById('topicText')
  const connectBtn = document.getElementById('connectBtn')
  const errorMsg = document.getElementById('errorMsg')
  const sendTopicText = document.getElementById('sendTopicText')
  const sendMsgText = document.getElementById('sendMsgText')
  const sendQosNumber = document.getElementById('sendQosNumber')
  const sendRetainCheckbox = document.getElementById('sendRetainCheckbox')
  const sendBtn = document.getElementById('sendBtn')
  const receiveMsgText = document.getElementById('receiveMsgText')
  let client

  /**
   * 连接/断开按钮
   */
  connectBtn.addEventListener('click', function () {
    if (client === undefined) {
      connectBtn.innerText = '连接中...'
      connectBtn.setAttribute('disabled', 'true')
      connect()
    } else {
      disconnect()
    }
  })

  /**
   * 连接
   */
  function connect() {
    const ip = ipText.value
    const port = Number(portNumber.value)
    const username = usernameText.value
    const password = passwordText.value
    const connectionTimeout = Number(connectionTimeoutNumber.value)
    const keepAliveInterval = Number(keepAliveIntervalNumber.value)
    const cleanSession = cleanSessionCheckbox.checked
    const automaticReconnect = automaticReconnectCheckbox.checked

    client = new Paho.Client(ip, port, '/mqtt', 'mqtt_' + new Date().getTime())
    client.onConnectionLost = onConnectionLostCallback
    client.onMessageArrived = onMessageArrivedCallback
    client.connect({
      userName: username,
      password: password,
      timeout: connectionTimeout,
      keepAliveInterval: keepAliveInterval,
      cleanSession: cleanSession,
      reconnect: automaticReconnect,
      onSuccess: onSuccessCallback,
      onFailure: onFailureCallback
    })
  }

  /**
   * 断开
   */
  function disconnect() {
    if (client !== undefined) {
      client.disconnect()
      client = undefined
      connectStatus(false)
    }
  }

  /**
   * 改变连接状态显示
   */
  function connectStatus(status) {
    connectBtn.removeAttribute('disabled')
    sendBtn.removeAttribute('disabled')
    if (status) {
      connectBtn.innerText = '断开'
      sendBtn.removeAttribute('disabled')
    } else {
      connectBtn.innerText = '连接'
      sendBtn.setAttribute('disabled', 'true')
    }
  }

  /**
   * 连接成功回调
   */
  function onSuccessCallback() {
    connectStatus(true)
    client.subscribe(topicText.value)
  }

  /**
   * 连接失败回调
   */
  function onFailureCallback(e) {
    connectStatus(false)
    client = undefined
    errorMsg.value = e.errorMessage + '\n' + errorMsg.value
  }

  /**
   * 连接丢失回调
   */
  function onConnectionLostCallback(res) {
    errorMsg.value = res.errorMessage + '\n' + errorMsg.value
  }

  /**
   * 消息到达回调
   */
  function onMessageArrivedCallback(res) {
    receiveMsgText.value = 'topic:' + res.topic + '\n' + 'retain:' + res.retained + '\n' + 'qos:' + res.qos + '\n' + 'msg:' + res.payloadString + '\n' + '\n' + receiveMsgText.value
    console.log(res)
  }

  /**
   * 发送消息
   */
  sendBtn.addEventListener('click', function () {
    client.send(sendTopicText.value, sendMsgText.value, Number(sendQosNumber.value), sendRetainCheckbox.checked)
  })

</script>
</html>
